package com.wlf.service.impl;

import com.rabbitmq.tools.json.JSONUtil;
import com.wlf.constant.Constants;
import com.wlf.controller.sendMsgController;
import com.wlf.dao.MqMessageMapper;
import com.wlf.entity.MqMessage;
import com.wlf.entity.MqMessageExample;
import com.wlf.service.IMqMessageService;
import com.wlf.util.CommonFunctions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
* @author 作者 危凌峰:
* @version 创建时间：2021年4月28日 上午9:39:49
*/
@Service
@Transactional
public class MqMessageServiceImpl implements IMqMessageService{

	private static org.slf4j.Logger logger = LoggerFactory.getLogger(MqMessageServiceImpl.class);

	@Autowired
	private MqMessageMapper mqMessageMapper;


	@Override
	public MqMessage getMqMessage(MqMessage mqMessage) {

		MqMessageExample example =new MqMessageExample();
		example.createCriteria().andBusinessIdEqualTo(mqMessage.getBusinessId())
				.andDeletedEqualTo(Constants.DELETED);

		List<MqMessage> mqMessageList=mqMessageMapper.selectByExample(example);
		if(CommonFunctions.isEmpty(mqMessageList)){
			return null;
		}
		return mqMessageList.get(0);
	}

	@Override
	public void insert(MqMessage mqMessage) {
		mqMessageMapper.insert(mqMessage);
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			public void beforeCommit(boolean readOnly) {
				logger.info("事务开始提交");
			}
			public void afterCommit() {
				logger.info("事物已经提交:{}", com.alibaba.fastjson.JSONObject.toJSONString(mqMessage));
			}
		});
		logger.info("任务已经结束！");
	}

	@Override
	public void updateMqMessageStatus(MqMessage mqMessage) {
		MqMessage record =new MqMessage();
		record.setIsCustomer(Constants.ONE);
		record.setUpdatedBy(2);
		record.setUpdatedTime(new Date());

		MqMessageExample example=new MqMessageExample();
		example.createCriteria().andBusinessIdEqualTo(mqMessage.getBusinessId())
				.andDeletedEqualTo(Constants.ZERO);

		mqMessageMapper.updateByExampleSelective(record,example);

	}

	public List<MqMessage> getMqMessageList(MqMessage mqMessage) {

		MqMessageExample example =new MqMessageExample();
		example.createCriteria().andDeletedEqualTo(mqMessage.getDeleted())
		.andIsCustomerEqualTo(mqMessage.getIsCustomer());

		return mqMessageMapper.selectByExample(example);
	}
}
